<?php
namespace app\logic;

use think\facade\Db;

class MenuHelper
{
    public static function get_menu_names($menu_ids) {
        if (empty($menu_ids)) return '';

        $list = DataHelper::select("tb_menu", "id in ($menu_ids)", [
            'order_by' => 'idx desc',
            'with_power' => false
        ]);
        $menu_names = '';
        foreach ($list as $item) {
            $menu_names .= $item["title"].',';
        }
        $menu_names = trim($menu_names, ',');

        return [$menu_ids, $menu_names];
    }

    public static function expand_menu_ids($menu_ids) {
        $menu_ids_new = [];
        $menu_titles_new = [];

        $menu_ids = explode(',', $menu_ids);
        foreach ($menu_ids as $menu_id) {
            if ($menu_id > 0) {
                $menu = DataHelper::find_by_id('tb_menu', $menu_id);

                $menu_ids_new[] = $menu_id;
                $menu_titles_new[] = $menu['title'];

                if ($menu['pid'] > 0) {
                    $menu_ids_new[] = $menu['pid'];
                    $menu_titles_new[] = $menu['pname'];
                }
            }
        }

        $menu_ids_new = array_unique($menu_ids_new);
        $menu_titles_new = array_unique($menu_titles_new);

        return [$menu_ids_new, $menu_titles_new];
    }

    public static function load_role_menu($pid, $role_id, $all_menu_list) {

        $role = DataHelper::find_by_id('tb_role', $role_id);
        $all_role_menu_ids = MenuHelper::expand_menu_ids($role['menu_ids'])[0];


        $list = DataHelper::select('tb_menu', [
            [ 'pid', '=', $pid ],
            [ 'id', 'in', $all_role_menu_ids ],
            [ 'status', '=', 0 ],
        ], "idx desc", [ 'with_power' => false ]);

        foreach ($list as &$item) {
            $children = self::load_role_menu($item['id'], $role_id, $all_menu_list);
            $item['children'] = $children;
        }

        return $list;
    }

    public static function load_menu($pid = 0, $checked_ids = []) {

        $list = DataHelper::select('tb_menu', [
            [ 'pid', '=', $pid ],
            [ 'status', '=', 0 ],
        ], "idx desc", [ 'with_power' => false ]);

        foreach ($list as &$item) {
            if (in_array($item['id'], $checked_ids)) {
                $item['checked'] = true;
            }
        }

        foreach ($list as &$item) {
            $children = self::load_menu($item['id'], $checked_ids);
            $item['children'] = $children;
        }

        return $list;
    }
}